import React from 'react';
import { Card, Button, Table, Space, Modal, TableProps, message } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaOverseasStudySrv } from '@/service/teacher';
import { countries } from '@/constant/country';
import { isPermissionOperate } from '@/component/permission-button';

const OnResearch: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const { id: teacher_id } = useParams();
  const columns: TableProps['columns'] = [
    {
      title: '开始日期',
      dataIndex: 'start_date',
      key: 'start_date',
    },
    {
      title: '结束日期',
      dataIndex: 'end_date',
      key: 'end_date',
    },
    {
      title: '国家/地区',
      dataIndex: 'country_region',
      key: 'country_region',
      render: (text: any) => {
        return _.find(countries, { value: String(text) })?.label;
      },
    },
    {
      title: '研修/访学机构名称',
      dataIndex: 'training_institution_name',
      key: 'training_institution_name',
    },
    {
      title: '项目名称',
      dataIndex: 'project_name',
      key: 'project_name',
    },
    {
      title: '项目组织单位名称',
      dataIndex: 'organizing_institution_name',
      key: 'organizing_institution_name',
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '开始日期',
          name: 'start_date',
          key: 'start_date',
          required: true,
          inputType: InputType.date,
        },
        {
          label: '结束日期',
          name: 'end_date',
          key: 'end_date',
          required: true,
          inputType: InputType.date,
        },
        {
          label: '国家(地区)',
          name: 'country_region',
          key: 'country_region',
          required: true,
          inputType: InputType.select,
          renderOption: countries,
        },
        {
          label: '研修(访学)机构名称',
          name: 'training_institution_name',
          key: 'training_institution_name',
          textRange: [0, 20],
        },
        {
          label: '项目名称',
          name: 'project_name',
          key: 'project_name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '项目组织单位名称',
          name: 'organizing_institution_name',
          key: 'organizing_institution_name',
          textRange: [0, 20],
        },
      ],
    },
  ];

  const [formValue, setFormValue] = React.useState({});
  const [dataSource, setDataSource] = React.useState([]);
  const [currentRowId, setCurrentRowId] = React.useState(null);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaOverseasStudySrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };
  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({});
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    const { data } = await TeaOverseasStudySrv.detail(record.overseas_study_id);

    const params = {
      ...data,
    };

    setCurrentRowId(record.overseas_study_id);
    setFormValue(params);

    setIsEdit(true);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    Modal.confirm({
      title: '删除',
      content: `是否删除${record.start_date}-${record.end_date},参加${record.project_name} **** 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaOverseasStudySrv.delete(record.overseas_study_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = await formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id,
    };

    params.start_date = utils.formatTime(values.start_date);
    params.end_date = utils.formatTime(values.end_date);

    if (isEdit) {
      params.overseas_study_id = currentRowId;
    }
    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaOverseasStudySrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      fetchData();
      setCurrentRowId(null);
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="海外研修（访学）" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '海外研修（访学）编辑' : '海外研修（访学）详情') : '海外研修（访学）新增'}
        visible={showFormModel}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

OnResearch.defaultProps = {
  isEditPanel: true,
};

export default OnResearch;
